# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(optparse)
library(stringr)
library(magrittr)
library(tidyverse)
library(tools)
library(extrafont)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--config", default = "calculate_config.txt", type = "character", help = "config file"),
  make_option("--pc", default = "", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))
font_import(paths = c("/usr/share/fonts/myFonts"),recursive =F, prompt = F)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))
source(str_c(scriptPath, "/parse_config_json.R"))
baseFamily <- fontFamily

configData <- read_tsv(opt$config, col_names = F) %>%
  set_colnames(c("arg", "value"))

configData

classColDf <- tibble(ClassNote = plotConfigJson$color$groups, col = plotConfigJson$color$colors)
colors <- classColDf %>%
  deframe()
diffFileNames <- configGet(configData, "diffFiles") %>%
  str_split(":") %>%
  unlist()

diffFileNames

dataList <- diffFileNames %>%
  map(function(fileName) {
    newFileName <- fileName %>%
      str_split("/") %>%
      unlist() %>%
      tail(., 2) %>%
      str_c(collapse = "_") %>%
      str_replace(., ".csv$", ".txt")
    data <- read_tsv(str_c(newFileName))
    metabolites <- data$Metabolite
    list(metabolites = metabolites)
  })

labels<-classColDf %>%
  .$ClassNote
datas <- dataList %>%
  map(~.x$metabolites) %>%
  purrr::set_names(labels)

size <- length(labels)
labelsStr <- labels %>%
  map_chr(~str_c(.x, "\n"))

pdfFileName <- str_c("Venn_Plot.pdf")
maxCharNum <- labelsStr %>%
  map_dbl(~str_length(.x)) %>%
  max()
defaultWidth <- 8 + maxCharNum * 0.25
defaultHeight <- defaultWidth
finalWidth <- getFinalWidth(width, defaultWidth, opt$pc)
finalHeight <- getFinalHeight(height, defaultHeight, opt$pc)

pdf(pdfFileName, width = finalWidth, height = finalHeight)
par(mar = c(2, 0, 2, 6) + 0.1, family = baseFamily)
vennPlot(datas,colors,baseFamily)
dev.off()




















